//
//  WMHelper.m
//  WeightMaster
//
//  Created by sungeo on 15/8/14.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WMHelper.h"
#import "WMWeight.h"
#import <NSDate+DateTools.h>

@implementation WMHelper

+ (NSNumber *)BMIForWeight:(NSNumber *)weight height:(NSNumber *)height{
    float weightValue = [weight floatValue];
    float heightValue = [height floatValue] / 100;
    
    float bmi = weightValue / (heightValue * heightValue);
    return @(bmi);
}

+ (WMWeightRange)weightRangeForWeights:(NSArray *)weights{
    WMWeightRange range;
    
    NSArray * sorted = [[self class] sortingWeightsByValue:weights];
    const NSInteger count = sorted.count;
    if (count == 0) {
        return range;
    }
    
    range.low = [[((WMWeight *)sorted[0]) value] floatValue];
    range.high = [[((WMWeight *)sorted[count - 1]) value] floatValue];
    return range;
}


// 排序函数，将所有体重值按由小到大排序
+ (NSArray *)sortingWeightsByValue:(NSArray *)weights{
    NSArray * sorted = [weights sortedArrayUsingComparator:^(id w1, id w2){
        float data1 = [[((WMWeight *)w1) value] floatValue];
        float data2 = [[((WMWeight *)w2) value] floatValue];
        
        if(data1 < data2){
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
    }];
    
    return sorted;
}

/**
 *  根据记录体重的日子，升序排序
 *
 *  @return 排序后的体重数组的拷贝
 */
+ (NSArray *)sortingWeightsByMeasuringDate:(NSArray *)weights{
    NSArray * sorted = [weights sortedArrayUsingComparator:^(id w1, id w2){
        NSDate * date1 = [((WMWeight *)w1) measuringDate];
        NSDate * date2 = [((WMWeight *)w2) measuringDate];
        
        if([date2 isLaterThan:date1]){
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
    }];
    
    return sorted;
}


+ (NSString *)stringValueForWeight:(NSNumber *)value withUnit:(NSNumber *)unit{
    float floatValue = value.floatValue;
    if ([unit integerValue] == WMWeightUnitJin) {
        floatValue *= 2;
    }
    
    NSString * floatString = [NSString stringWithFormat:@"%.1f", floatValue];
    
    if (floatString.length > 0 && [floatString hasSuffix:@".0"]) {
        NSRange range = NSMakeRange(floatString.length - 2, 2);
        floatString = [floatString stringByReplacingCharactersInRange:range withString:@""];
    }
    
    return floatString;
}

+ (NSString *)stringValueForGender:(WMGender)gender{
    switch (gender) {
        case WMGenderMale:
            return @"男";
        case WMGenderFemale:
            return @"女";
    }
}

+ (NSString *)stringValueForUnit:(NSNumber *)weightUnit{
    WMWeightUnit unit = (WMWeightUnit)weightUnit.integerValue;
    switch (unit) {
        case WMWeightUnitKiloGram:
            return @"公斤";
        case WMWeightUnitJin:
            return @"斤";
    }
}

+ (NSString *)stringValueForHeight:(float)height{
    return [NSString stringWithFormat:@"%d厘米", (int)height];
}

@end
